import Vue from 'vue'
import VueRouter from 'vue-router'
//引入Login组件
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Setting from '../components/Setting.vue'
import Welcome from '../components/Welcome.vue'
import UserList from '../components/super/UserList.vue'

Vue.use(VueRouter)

const routes = [
  // redirect 默认路径
  {path:'/',redirect:"/login"},
  {path:'/login',component:Login},
  {
    path:'/home',component:Home,
    redirect:"/welcome",//从定向到主题内容页面
    children:[//子页面
      {path:'/welcome',component:Welcome},
      {path:'/user',component:UserList}
    ]
  },
  {path:'/setting',component:Setting}
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫: 出现undefined错误处理
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location,onResolve,onReject){
  if(onResolve || onReject) return originalPush.call(this,location,onResolve,onReject)
  return originalPush.call(this,location).catch(err => err)
}

// 挂载路由导航守卫
// to 将要访问
// from 从哪来
// next 接下来，next(url)重定向url上 next()继续访问
router.beforeEach((to,from,next) => {
  // 登录页放行
  if(to.path == '/login') return next();
  // 获取session的user
  const userFlag = window.sessionStorage.getItem("user");
  // 无值返回登录页面
  if(userFlag == null) return next("/login");
  next();    
})

export default router
